const SERVICE = require("../../service.js");
const URL = SERVICE.URL;
Page({
  data:{
    SilderValue:30
  },
  onLoad(options){
    this.setData({
      showImgUrl: options.imgUrl
    });
    this.RecognitionImg(URL.uploadingImg, options.imgUrl);
  },
  onShareAppMessage(){

  },
  ChangeSilder(){
    let td = this.data;
    this.RecognitionImg(URL.uploadingImg, td.showImgUrl);
  },
  ChangingSilder(e){
    let SilderValue = e.detail.value;
    this.setData({
      SilderValue
    });
  },
  uploadingImg(){
    let _this = this;    
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor:"#f7982a",
      success:function(res){
        if (!res.cancel){
          let tapIndex = res.tapIndex;
          if (tapIndex == 0){
            _this.chooseWxImage("album");
          } else if (tapIndex == 1){
            _this.chooseWxImage("camera");
          }
        }
      }
    })
  },
  chooseWxImage(type){
    let _this = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      success: function(res) {
        let tempFilePath = res.tempFilePaths[0];        
        _this.setData({
          showImgUrl: tempFilePath
        });
        _this.RecognitionImg(URL.uploadingImg, tempFilePath);
      },
    })
  },
  RecognitionImg(url,filePath){
    let _this = this,td = _this.data;
    wx.getImageInfo({
      src: filePath,
      success:function(res){
        let ratio =  parseFloat(res.width)/parseFloat(res.height);
        _this.setData({
          imgWidth:'width:'+ parseInt(490* ratio) + 'rpx'
        });
        wx.showLoading({
          title: "识别中...",
        });
        wx.uploadFile({
          url: url,
          filePath: filePath,
          name: "images",
          formData: {
            threshold: (td.SilderValue * 0.01),
            image_width: parseInt(490 * ratio) / 2,
            image_high: 490
          },
          success: function (res) {
            wx.hideLoading();
            let RecognitinoData = JSON.parse(res.data);
            for (let i = 0; i < RecognitinoData.results.length; i++) {
              RecognitinoData.results[i].score = parseFloat(RecognitinoData.results[i].score * 100).toFixed(2);
            }
            _this.setData({
              RecognitinoData
            });
          }
        })
      }
    });
   
  }
});